/**
 * Program   :   FreeMarkerToolImpl.java
 * Author    :   Troy.zhou
 * Create    :   2011-4-15 下午11:16:03
 *
 * Copyright 2008 by Tongfu Information Technology Co. Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information
 * of Tongfu Information Technology Co. Ltd. ("Confidential Information").  You
 * shall not disclose such Confidential Information and shall use
 * it only in accordance with the terms of the license agreement
 * you entered into with Tongfu Information Technology Co. Ltd.
 * 
 */
package com.tongfusoft.utils.template.impl;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.tongfusoft.utils.template.IFreeMarkerTool;

import freemarker.template.Configuration;
import freemarker.template.TemplateException;

/**
 * @author Troy
 * 
 */
public class FreeMarkerToolImpl implements IFreeMarkerTool {
	private Log log = LogFactory.getLog(FreeMarkerToolImpl.class);
	private static final String DEFAULT_TEMPLATE_PATH;
	private static final String DEFAULT_INSTANCE_NAME = "default";
	private static Map<String, IFreeMarkerTool> instances = new HashMap<String, IFreeMarkerTool>();
	static {
		DEFAULT_TEMPLATE_PATH = new File(FreeMarkerToolImpl.class.getClassLoader().getResource("").getPath()).getParent() + "/template/"; // "WEB-INF/template";
		instances.put(DEFAULT_INSTANCE_NAME, new FreeMarkerToolImpl(DEFAULT_TEMPLATE_PATH));
	}

	public static IFreeMarkerTool getDefaultInstance() {
		return instances.get(DEFAULT_INSTANCE_NAME);
	}

	public static IFreeMarkerTool loadInstance(String templatePath) {
		if (instances.containsKey(templatePath)) {
			return instances.get(templatePath);
		}
		FreeMarkerToolImpl temp = new FreeMarkerToolImpl(templatePath);
		instances.put(templatePath, temp);
		return temp;
	}

	private Configuration cfg;
	private String templatePath;

	private FreeMarkerToolImpl(String templatePath) {
		this.templatePath = templatePath;
		init();
	}

	public void init() {
		// 初始化操作
		try {
			cfg = new Configuration();
			cfg.setDirectoryForTemplateLoading(new File(templatePath));
		} catch (IOException e0) {
			try {
				templatePath = Thread.currentThread().getContextClassLoader().getResource("").getPath() + "../template/";
				cfg.setDirectoryForTemplateLoading(new File(templatePath));
			} catch (IOException e1) {
				try {
					templatePath = new File(FreeMarkerToolImpl.class.getClassLoader().getResource("").getPath()).getParent() + "/tsp2/WEB-INF/template/";
					cfg.setDirectoryForTemplateLoading(new File(templatePath));	// for jetty
				} catch (Exception e2) {
					try {
						// windows 测试用
						cfg.setDirectoryForTemplateLoading(new File(
								"D:/eclipse/eclipse34/workspace/tsp2/src/main/webapp/WEB-INF/template/"));	// test
					} catch (Exception e3) {
						// Unix 测试用
						try {
							cfg.setDirectoryForTemplateLoading(new File(
									"/u01/app/oracle/fmw/user_projects/domains/tsp_domain/servers/tsp/tmp/_WL_user/tsp2/ls8p7/war/WEB-INF/template"));
						} catch (IOException e4) {
							try {
								cfg.setDirectoryForTemplateLoading(new File(
										"/u01/app/oracle/fmw/user_projects/domains/tsp_domain/servers/tsp/tmp/_WL_user/tsp2/*/war/WEB-INF/template"));
							} catch (IOException e5) {
								// /u01/app/oracle/fmw/tsp2/WEB-INF/template/
								log.error("模板路径:" + templatePath);
								log.error("找不到指定模板文件夹");
								e5.printStackTrace();
							}
						}
					}
				}
			}
		}
		log.debug("最终加载目录为:" + templatePath);
		cfg.setEncoding(Locale.CHINA, "UTF-8");
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.tongfusoft.appec.template.util.IFreeMarkerTool#transform(java.lang
	 * .String, java.util.Map)
	 */
	@Override
	public String transform(String styleSheet, Map<String, Object> root) {
		StringWriter sw = new StringWriter();
		try {
			cfg.getTemplate(buildSuffix(styleSheet)).process(root, sw);
		} catch (TemplateException e) {
			System.out.println("now search template path is :" + templatePath);
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("now search template path is :" + templatePath);
			e.printStackTrace();
		}
		return sw.toString();
	}

	@Override
	public boolean saveTofile(String styleSheet, Map<String, Object> data, String fileName) {
		try {
			FileWriter fos = new FileWriter(new File(fileName));
			cfg.getTemplate(buildSuffix(styleSheet)).process(data, fos);
			fos.flush();
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		} catch (TemplateException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	/**
	 * @param stylesheet
	 * @return
	 */
	private String buildSuffix(String styleSheet) {
		if (styleSheet.indexOf(".ftl") == -1) {
			styleSheet = styleSheet + ".ftl";
		}
		return styleSheet;
	}

	/**
	 * @param templatePath
	 *            the templatePath to set
	 */
	public void setTemplatePath(String templatePath) {
		this.templatePath = templatePath;
	}
}
